package com.xbniao.gcfs.common.util.ExportExcel;

import org.apache.commons.lang3.StringUtils;
import org.apache.poi.hssf.usermodel.HSSFWorkbook;
import org.apache.poi.ss.usermodel.Workbook;
import org.apache.poi.xssf.usermodel.XSSFWorkbook;

import java.io.*;

/**
 * @Author:wangbin.
 * @Description.
 * @Date:Created in 15:02 2018/4/27.
 * @Modified By:
 */
public abstract class ExportExcelBase {

    /**
     * 导出数据
     * @param sourcePath
     * @param targetPath
     * @param data
     */
    public void export(String sourcePath, String targetPath, Object data)
    {
        InputStream is = null;
        OutputStream os = null;
        try {
            File file = new File(sourcePath);
            is = new FileInputStream(file);
            Workbook wb = read(is, !StringUtils.endsWith(sourcePath, ".xlsx"),data);

            os = new FileOutputStream(targetPath);//写数据到这个路径上
            wb.write(os);
            os.flush();
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            try {
                os.close();
                is.close();
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
    }

    /**
     * 重载的导出（浏览器直接下载）
     * @param sourcePath
     * @param os
     * @param data
     */
    public void export(String sourcePath, OutputStream os, Object data)
    {
        InputStream is = null;
        try {
            File file = new File(sourcePath);
            is = new FileInputStream(file);
            Workbook wb = read(is, !StringUtils.endsWith(sourcePath, ".xlsx"), data);

            wb.write(os);
            //os.flush();
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            try {
                is.close();
                os.close();
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
    }

    /**
     * 读取一个excel文件
     * @param inputStream
     * @param isExcel2003
     * @throws Exception
     */
    public Workbook read(InputStream inputStream, boolean isExcel2003,Object data){
        /** 根据版本选择创建Workbook的方式 */
        Workbook wb = null;
        try {
            if (isExcel2003) {
                wb = new HSSFWorkbook(inputStream);
            } else {
                wb = new XSSFWorkbook(inputStream);
            }
            read(wb,data);
        } catch (Exception e) {
            e.printStackTrace();
        }
        return wb;
    }

    public abstract void read(Workbook wb,Object data) throws Exception;
}
